package com.qunar.homework4.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.qunar.homework4.dao.ParagraphDao;
import com.qunar.homework4.enums.StatusEnum;
import com.qunar.homework4.model.Paragraph;
import com.qunar.homework4.model.dto.TextBody;
import com.qunar.homework4.model.vo.CounterResult;
import com.qunar.homework4.utils.ContentUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class ContentCounterService {

    @Resource
    private ParagraphDao paragraphDao;

    @Resource
    private OkHttpClient ohc;

    @Resource
    private Request.Builder rb;

    public CounterResult counterContent(String url, String tittleField, String contentField){
        CounterResult<Paragraph> result = new CounterResult<>();
        try {
            String responseBody = ohc.newCall(rb.build()).execute().body().string();
            if (StringUtils.isBlank(responseBody)){
                result.setStatus(StatusEnum.FAIL.getCode());
            }else {
                TextBody textBody = JSON.parseObject(responseBody, new TypeReference<TextBody>(){});
                if (textBody == null){
                    result.setStatus(StatusEnum.FAIL.getCode());
                }else {
                    Paragraph paragraph = ContentUtils.counterContent(textBody.getContent());
                    paragraph.setTitle(textBody.getTitle());
                    paragraph.setUrl(url);
                    int affectRows = paragraphDao.insert(paragraph);
                    if (affectRows > 0){
                        result.setStatus(StatusEnum.SUCCESS.getCode());
                    }else {
                        result.setStatus(StatusEnum.FAIL.getCode());
                    }
                }
            }
        }catch (Exception e){
            result.setStatus(StatusEnum.FAIL.getCode());
            result.setMessage(e.getMessage());
            log.error("ContentCounterService counterContent error:", e);
        }
        return result;
    }

    public CounterResult<List<Paragraph>> queryAllCounterResult(){
        CounterResult<List<Paragraph>> result = new CounterResult<>();
        try {
            result.setStatus(StatusEnum.SUCCESS.getCode());
            List<Paragraph> resList = paragraphDao.selectAll();
            result.setData(resList);
        }catch (Exception e){
            result.setStatus(StatusEnum.FAIL.getCode());
            result.setMessage(e.getMessage());
            log.error("ContentCounterService queryAllCounterInfo error:", e);
        }
        return result;
    }
}
